﻿using System;
using System.Globalization;
using Monkey.Warrenty.Biz;
using Monkey.Warrenty.Constants;
using Monkey.Warrenty.EntityModel;
using Monkey.Warrenty.Enum;
using MonkeyWarranty.Web.Common;

namespace MonkeyWarranty.Web.InstantTickets
{
    public partial class NewService : System.Web.UI.Page
    {
        private static InstantTicketBiz _instantTicketBiz;
        private static InstantTicketBiz InstantTicketManager
        {
            get { return _instantTicketBiz ?? (_instantTicketBiz = new InstantTicketBiz()); }
        }

        private static CategoryBiz _categoryBiz;
        private static CategoryBiz CategoryManager
        {
            get { return _categoryBiz ?? (_categoryBiz = new CategoryBiz()); }
        }

        private static CustomerBiz _customerBiz;
        private static CustomerBiz CustomerManager
        {
            get { return _customerBiz ?? (_customerBiz = new CustomerBiz()); }
        }

        private static EmployeeBiz _employeeBiz;

        private static EmployeeBiz EmployeeManager
        {
            get { return _employeeBiz ?? (_employeeBiz = new EmployeeBiz()); }
        }

        private long _ticketId;
        private long TicketId
        {
            get
            {
                if (_ticketId <= 0) long.TryParse(Request.Params["ticketId"], out _ticketId);
                return _ticketId;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (WarrantyCommon.CurrrentEmployee == null)
            {
                Response.Redirect("~/Logon.aspx");
                return;
            }

            if (!WarrantyCommon.CurrrentEmployee.HasRole(RoleConstant.AdminDichVu))
            {
                Response.Redirect("~/NoPermission.aspx");
            }

            if (!IsPostBack)
            {
                if (TicketId <= 0)
                {
                    lblErrorMessage.Text = Resources.GlobalStrings.InstantTicketNotExisted;
                    btnSave.Enabled = false;
                    return;
                }

                LoadData();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            errorMessage.Visible = false;
            lblErrorMessage.Text = string.Empty;

            // validate inputs
            var serviceId = hidServiceId.Value;
            if (string.IsNullOrEmpty(serviceId))
            {
                errorMessage.Visible = true;
                lblErrorMessage.Text = Resources.GlobalStrings.ServiceIsRequired;
                return;
            }

            var descrition = txtDescription.Text;
            var note = txtNote.Text;

            var ticketService = new InstantTicket_Service
            {
                InstantTicketId = TicketId,
                ServiceId = int.Parse(serviceId),
                Description = descrition,
                Note = note
            };

            int quantity;
            if (int.TryParse(txtQuantity.Text.Trim(), out quantity))
            {
                ticketService.Quantity = quantity;
            }

            int serviceTypeId;
            if (int.TryParse(ddlServiceTypes.SelectedValue, out serviceTypeId))
            {
                ticketService.ServiceTypeId = serviceTypeId;
            }

            int errorId;
            if (int.TryParse(ddlErrors.SelectedValue, out errorId))
            {
                ticketService.ErrorId = errorId;
            }

            int employeeId;
            if (int.TryParse(ddlEmployees.SelectedValue, out employeeId) && employeeId > 0)
            {
                ticketService.EmployeeId = employeeId;
            }

            ticketService.InstantServiceStateId = (int) InstantServiceStatus.Received;

            DateTime startDate;
            if (DateTime.TryParseExact(txtStartDate.Text.Trim(), "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out startDate))
            {
                ticketService.StartDate = startDate;
            }
            else
            {
                ticketService.StartDate = null;
            }

            DateTime endDate;
            if (DateTime.TryParseExact(txtEndDate.Text.Trim(), "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out endDate))
            {
                ticketService.EndDate = endDate;
            }
            else
            {
                ticketService.EndDate = null;
            }

            // Call Biz Save Product
            InstantTicketManager.CreateTicketService(ticketService);

            errorMessage.Visible = true;
            Response.Redirect(string.Format("Edit.aspx?id={0}#tabs-1", TicketId));
        }

        private void LoadData()
        {
            // instant ticket
            var ticket = InstantTicketManager.GetById(TicketId);
            if (ticket == null)
            {
                return;
            }
            ltrTicketCode.Text = ticket.Code;
            ltrContent.Text = ticket.TicketContent;
            ltrDistance.Text = string.Format("{0:0.00}", ticket.Distance);
            ltrReceivedDate.Text = string.Format("{0:dd/MM/yyyy HH:mm}", ticket.CreatedDate);
            if (!string.IsNullOrEmpty(ticket.Description))
            {
                ltrDescription.Text = string.IsNullOrEmpty(ticket.Description) ? string.Empty : ticket.Description.Replace("\n", "<br />");
            }

            txtStartDate.Text = string.Format("{0:dd/MM/yyyy HH:mm}", DateTime.Now);

            // customer
            var customer = CustomerManager.GetById(ticket.CustomerId);
            if (customer != null)
            {
                ltrCustomerName.Text = customer.Name;
                ltrCustomerAddress.Text = customer.Address;
                ltrCustomerPhone.Text = customer.Phone;
                ltrCustomerEmail.Text = customer.Email;
            }

            // service types
            var serviceTypes = CategoryManager.GetAllServiceTypes();
            serviceTypes.Insert(0, new ServiceType { Id = 0, Name = string.Empty });
            ddlServiceTypes.DataTextField = "Name";
            ddlServiceTypes.DataValueField = "Id";
            ddlServiceTypes.DataSource = serviceTypes;
            ddlServiceTypes.DataBind();

            // errors
            var errors = CategoryManager.GetAllErrors();
            errors.Insert(0, new Error { Id = 0, Name = string.Empty });
            ddlErrors.DataTextField = "DisplayName";
            ddlErrors.DataValueField = "Id";
            ddlErrors.DataSource = errors;
            ddlErrors.DataBind();

            // technical employees
            var employees = EmployeeManager.GetEmployeesOfRole((int)UserRole.KythuatDichVu);
            employees.Insert(0, new Employee { Id = 0, Name = string.Empty });
            ddlEmployees.DataSource = employees;
            ddlEmployees.DataValueField = "Id";
            ddlEmployees.DataTextField = "Name";
            ddlEmployees.DataBind();
        }
    }
}